import { stringify } from 'querystring';
import { Reducer, Effect } from 'umi';
import { history } from 'umi';

import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import storage from '@/utils/storage';
import memory from '@/utils/memory';
import { message } from 'antd';

export type StateType = {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
};

export type LoginModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
};

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call }) {
      try {
        const { data, status, msg } = yield call(fakeAccountLogin, {
          payload: {
            data: {
              ...payload
            }
          }
        });
        storage.saveUser(data) // 存储用户信息到local
        memory.user = data // 存储用户信息到内存
        // Login successfully
        if (status === 0) {
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          message.success('🎉 🎉 🎉  登录成功！');
          let { redirect } = params as { redirect: string };
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = '/';
              return;
            }
          }
          history.replace(redirect || '/');
        }else {
          message.error(msg)
        }

        // yield put({
        //   type: 'changeLoginStatus',
        //   payload: response,
        // });
        // // Login successfully
        // if (response.status === 'ok') {
        //   const urlParams = new URL(window.location.href);
        //   const params = getPageQuery();
        //   message.success('🎉 🎉 🎉  登录成功！');
        //   let { redirect } = params as { redirect: string };
        //   if (redirect) {
        //     const redirectUrlParams = new URL(redirect);
        //     if (redirectUrlParams.origin === urlParams.origin) {
        //       redirect = redirect.substr(urlParams.origin.length);
        //       if (redirect.match(/^\/.*#/)) {
        //         redirect = redirect.substr(redirect.indexOf('#') + 1);
        //       }
        //     } else {
        //       window.location.href = '/';
        //       return;
        //     }
        //   }
        //   history.replace(redirect || '/');
        // }

      }catch (e) {
        console.log(e.message);
      }
    },

    logout() {
      // 删除储存的user数据
      storage.removeUser()
      memory.user = {}
      // 跳转到登录页
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};

export default Model;
